package com.cooba.activitys;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.dialog.DrawOutTipDialog;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.Md5Utils;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DrawOutActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout root_ll;
    private LinearLayout draw_out_money_top_ll;
    private ImageButton draw_out_money_back_btn;
    private TextView draw_out_money_phone;
    private ImageView draw_out_money_tip;
    private EditText draw_out_money_pay_name_et;
    private EditText draw_out_money_et;
    private TextView draw_out_money_error;
    private TextView draw_out_money_balance_tv;
    private TextView draw_out_money_comfirm_tv;
    private String balance;
    private Dialog mCameraDialog;
    private PopupWindow tipPopWindow;
    private TextView textView;
    private LinearLayout bottom_ll;
    private InputMethodManager imm;
    private Button dialog_comfirm_again_btn;
    private Button dialog_cancel_btn;
    private EditText dialog_input_pwd_et;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String drawmoney;
    private String temp;
    private Boolean isCanFlag=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw_out);
        balance = getIntent().getStringExtra("acount_balance");
        drawmoney = getIntent().getStringExtra("drawmoney");
        initView();
        initPopWindow();
        setListener();
        setData();
    }

    private void initPopWindow() {
        View tipview =this.getLayoutInflater().inflate(R.layout.draw_out_tip_dialog, null);
        textView= (TextView) tipview.findViewById(R.id.draw_out_tip_dialog_tv);
        tipPopWindow = new PopupWindow(tipview, CommonUtil.dip2px(this,270),
                ViewGroup.LayoutParams.WRAP_CONTENT);
        tipPopWindow.setFocusable(true);
        tipPopWindow.setOutsideTouchable(true);
        tipPopWindow.setBackgroundDrawable(new ColorDrawable());
    }

    private void setData() {
        String login_id = SharedPreferencesUtil.getData(DrawOutActivity.this, "login_id", "");
        if (!TextUtils.isEmpty(login_id)) {
            draw_out_money_phone.setText(login_id.substring(0, 3) + "****" + login_id.substring(7));
        }
        temp = "可用余额" + balance + "元";
        draw_out_money_balance_tv.setText(Utils.getColorSize(DrawOutActivity.this, temp, 4, temp.length() - 1, R.color.light_blue, 16));
    }

    private void setListener() {
        draw_out_money_back_btn.setOnClickListener(this);
        draw_out_money_tip.setOnClickListener(this);
        draw_out_money_comfirm_tv.setOnClickListener(this);
        draw_out_money_pay_name_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>0) {
                    String temp = s.toString();
                    String tem = temp.substring(temp.length()-1, temp.length());
                    Pattern p1 = Pattern.compile("[\u4e00-\u9fa5]");
                    Matcher m1 = p1.matcher(tem);
                    Pattern p2 = Pattern.compile("[a-zA-Z]");
                    Matcher m2 = p2.matcher(tem);
                    if (!m1.matches()&&!m2.matches()) {
                        Toast.makeText(DrawOutActivity.this, "姓名输入不合法!", Toast.LENGTH_SHORT).show();
                        s.delete(s.length()-1,s.length());
                        draw_out_money_comfirm_tv.setBackgroundColor(getResources().getColor(R.color.gray_1));
                        isCanFlag=false;
                    }else {
                        draw_out_money_comfirm_tv.setBackgroundColor(getResources().getColor(R.color.light_blue));
                        isCanFlag=true;
                    }

                }else {
                    draw_out_money_comfirm_tv.setBackgroundColor(getResources().getColor(R.color.gray_1));
                }
            }
        });

        draw_out_money_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {

                    float max = Float.parseFloat(balance);
                    float input = Float.parseFloat(draw_out_money_et.getText().toString());
                    if (input > max) {
                        //Toast.makeText(DrawOutActivity.this, "余额不足，无法提现", Toast.LENGTH_SHORT).show();
                        //draw_out_money_error.setVisibility(View.VISIBLE);
                        draw_out_money_balance_tv.setText("提现金额超限");
                        draw_out_money_balance_tv.setTextColor(getResources().getColor(R.color.red));
                        draw_out_money_comfirm_tv.setBackgroundColor(getResources().getColor(R.color.gray_1));
                    } else {
                        draw_out_money_balance_tv.setText(Utils.getColorSize(DrawOutActivity.this, temp, 4, temp.length() - 1, R.color.light_blue, 16));
                        draw_out_money_comfirm_tv.setBackgroundColor(getResources().getColor(R.color.light_blue));
                    }
                }else {
                    draw_out_money_comfirm_tv.setBackgroundColor(getResources().getColor(R.color.gray_1));
                }
            }
        });
        draw_out_money_et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus) {
//                    draw_out_money_top_ll.setVisibility(View.GONE);
//                } else {
//                    draw_out_money_top_ll.setVisibility(View.VISIBLE);
//                }
            }
        });

        root_ll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = root_ll.getRootView().getHeight() - root_ll.getHeight();
                if (heightDiff > 100) { //高度变小100像素则认为键盘弹出
                    //这里执行需要的处理
                    //Toast.makeText(DrawOutActivity.this,"tanchu",Toast.LENGTH_SHORT).show();
                    draw_out_money_top_ll.setVisibility(View.GONE);
                } else {
                    //Toast.makeText(DrawOutActivity.this,"guanbi",Toast.LENGTH_SHORT).show();
                    draw_out_money_top_ll.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void initView() {
        root_ll= (LinearLayout) findViewById(R.id.root_ll);
        draw_out_money_top_ll= (LinearLayout) findViewById(R.id.draw_out_money_top_ll);
        draw_out_money_back_btn = (ImageButton) findViewById(R.id.draw_out_money_back_ib);
        draw_out_money_phone = (TextView) findViewById(R.id.draw_out_money_phone);
        draw_out_money_tip = (ImageView) findViewById(R.id.draw_out_money_tip);
        draw_out_money_pay_name_et = (EditText) findViewById(R.id.draw_out_money_pay_name_et);
        draw_out_money_et = (EditText) findViewById(R.id.draw_out_money_et);
        draw_out_money_error= (TextView) findViewById(R.id.draw_out_money_error);
        draw_out_money_balance_tv = (TextView) findViewById(R.id.draw_out_money_balance_tv);
        draw_out_money_comfirm_tv = (TextView) findViewById(R.id.draw_out_money_comfirm_tv);
        bottom_ll= (LinearLayout) findViewById(R.id.bottom_ll);
        dialog_comfirm_again_btn= (Button) findViewById(R.id.dialog_comfirm_again_btn);
        dialog_cancel_btn= (Button) findViewById(R.id.dialog_cancel_btn);
        dialog_input_pwd_et= (EditText) findViewById(R.id.dialog_input_pwd_et);
        dialog_cancel_btn.setOnClickListener(this);
        dialog_comfirm_again_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.draw_out_money_back_ib:
                finish();
                break;
            case R.id.draw_out_money_tip:
                showPopWindow(v);
                break;
            case R.id.draw_out_money_comfirm_tv:
                if(TextUtils.isEmpty(draw_out_money_pay_name_et.getText().toString())){
                    Toast.makeText(DrawOutActivity.this,"姓名不能为空!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(draw_out_money_et.getText().toString())){
                    Toast.makeText(DrawOutActivity.this,"提现金额不能为空!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isCanFlag){
                    Toast.makeText(DrawOutActivity.this,"姓名输入不合法!",Toast.LENGTH_SHORT).show();
                    return;
                }
                float max = Float.parseFloat(drawmoney);
                float input = Float.parseFloat(draw_out_money_et.getText().toString());
                if (input<max){
                    Toast.makeText(DrawOutActivity.this,"低于提现限额"+drawmoney+"元,无法提现!",Toast.LENGTH_SHORT).show();
                    return;
                }
                float maxBalance = Float.parseFloat(balance);
                if (input>maxBalance){
                    Toast.makeText(DrawOutActivity.this,"提现金额超限!",Toast.LENGTH_SHORT).show();
                    return;
                }
                showComfirmDialog1();
                break;
            case R.id.dialog_cancel_btn:
                closeComfirmDialog();
                break;
            case R.id.dialog_comfirm_again_btn:
                doComfrimPwd();
                break;
            default:
                break;
        }
    }

    private void doComfrimPwd() {
        if (TextUtils.isEmpty(dialog_input_pwd_et.getText().toString())){
            Toast.makeText(DrawOutActivity.this,"密码不能为空!",Toast.LENGTH_SHORT).show();
            return;
        }
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        String password=dialog_input_pwd_et.getText().toString();
        String newPassword= Md5Utils.encodeBy32BitMD5(password);
        params.addBodyParameter("login_id", login_id);
        params.addBodyParameter("password", newPassword);
        String urldrawoutcheckpwd = ServerURL.httpUrl + ServerURL.drawoutcheckpwd;
        httpUtils.send(HttpRequest.HttpMethod.POST, urldrawoutcheckpwd, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei","密码校验成功"+responseInfo.result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseInfo.result.toString());
                    String status = jsonObject.get("status").toString();
                    if (status.equals("1")){
                        doDrawOut();
                        bottom_ll.setVisibility(View.GONE);
                    }else {
                        Toast.makeText(DrawOutActivity.this,"密码错误!",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei","密码校验失败"+msg);
            }
        });
    }

    private void doDrawOut() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        String name=draw_out_money_pay_name_et.getText().toString();
        String money=draw_out_money_et.getText().toString();
        params.addBodyParameter("user_id", login_id);
        params.addBodyParameter("money",money);
        params.addBodyParameter("name",name);
        String urldrawout = ServerURL.httpUrl + ServerURL.drawout;
        httpUtils.send(HttpRequest.HttpMethod.POST, urldrawout, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei","提现成功"+responseInfo.result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseInfo.result.toString());
                    String status = jsonObject.get("status").toString();
                    if (status.equals("1")){
                        Toast.makeText(DrawOutActivity.this,"提现成功!",Toast.LENGTH_SHORT).show();
                        setResult(1);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei","提现失败"+msg);
            }
        });
    }

    private void closeComfirmDialog() {
        bottom_ll.setVisibility(View.GONE);
        Animation animation2= AnimationUtils.loadAnimation(DrawOutActivity.this, R.anim.dialog_exit);
        bottom_ll.startAnimation(animation2);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(dialog_input_pwd_et.getWindowToken(), 0);
    }

    private void showComfirmDialog1() {
        bottom_ll.setVisibility(View.VISIBLE);
        Animation animation= AnimationUtils.loadAnimation(DrawOutActivity.this, R.anim.dialog_enter);
        bottom_ll.startAnimation(animation);
    }

    private void showPopWindow(View v) {
        if (tipPopWindow == null) {
            return;
        }
        if (tipPopWindow.isShowing()) {
            tipPopWindow.dismiss();
        } else {
            String text = "用于打款时校验该用户的手机号是否与用户姓名匹配，填写支付宝绑定的身份证姓名，谨慎填写，若校验不通过，申请提现将被打回。";
            textView.setText(text);
            tipPopWindow.showAsDropDown(v);
        }
    }

    private void showComfirmDialog(){
        mCameraDialog = new Dialog(this, R.style.my_dialog);
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.dialog_bottom_layout, null);
        root.findViewById(R.id.dialog_comfirm_again_btn).setOnClickListener(this);
        root.findViewById(R.id.dialog_cancel_btn).setOnClickListener(this);
        root.findViewById(R.id.dialog_input_pwd_et).setOnClickListener(this);
        mCameraDialog.setContentView(root);
        Window dialogWindow = mCameraDialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setWindowAnimations(R.style.dialogstyle); // 添加动画
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
//		lp.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度
//		lp.alpha = 9f; // 透明度
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();
        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        mCameraDialog.show();
    }
}
